/**
 * 
 */
package com.et114.components.acegi.resourcedetails;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.Element;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.util.Assert;


/**
 * @author guanhw
 */
public class DefaultTitleCacheManager implements TitleCache {
	private Log		logger	= LogFactory.getLog( DefaultTitleCacheManager.class );
	// ~ Instance fields
	// ========================================================
	private Cache	cache;

	// ~ Methods
	// ================================================================

	public void setCache ( Cache cache ) {
		this.cache = cache;
	}

	public Cache getCache ( ) {
		return this.cache;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.et114.components.acegi.resourcedetails.TitleCache#getUserFromCache(java.lang.String)
	 */
	public TitleDetails getUserFromCache ( String titleId ) {
		// TODO Auto-generated method stub
		Element element = null;
		try {
			Assert.notNull( cache , "缓存对象cache没有初始化！"  ) ;
			element = cache.get( titleId );
		} catch ( CacheException cacheException ) {
			throw new DataRetrievalFailureException( "Cache failure: " + cacheException.getMessage() , cacheException  );
		}

		if ( logger.isDebugEnabled() ) {
			//logger.debug( "Cache 是否存在: " + ( element != null ) + "; titleName: " + titleId );
		}

		if ( element == null ) {
			return null;
		} else {
			return ( TitleDetails ) element.getValue();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.et114.components.acegi.resourcedetails.TitleCache#putTitleInCache(com.et114.components.acegi.vo.TitleMsgVo)
	 */
	public void putTitleInCache ( TitleDetails title ) {
		// TODO Auto-generated method stub
		//Assert.isNull( cache , "缓存对象cache没有初始化！"  ) ;
		Element element = new Element( title.getTitleId(), title );
		if ( logger.isDebugEnabled() ) {
			logger.debug( "Cache put: " + element.getKey() );
		}
		cache.put( element );
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.et114.components.acegi.resourcedetails.TitleCache#removeTitleFromCache(java.lang.String)
	 */
	public void removeTitleFromCache ( String titleId ) {
		// TODO Auto-generated method stub
		Assert.notNull(  cache , "缓存对象cache没有初始化！"  ) ;
		cache.remove( titleId );
	}

}
